package com.ch3cooh.proxy;

import com.ch3cooh.proxy.pojo.ClassInfo;
import com.ch3cooh.rpc.controller.RpcService;
import com.ch3cooh.rpc.annotation.HttpRpc;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @功能: 创建代理对象工具类
 * @作者:chanson
 * @时间:2018/5/1 22:45
 */
public class ProxyObject implements InvocationHandler{

    private Class<?> target;

    /**
     * 通过接口使用 动态代理 生成对应的实现类
     * @param target    要代理的对象class
     * @return
     */
    public Object bind(Class<?> target) {
        this.target = target;
     //   ProxyRegistry.proxyMap.put(target.getName() , )
        return Proxy.newProxyInstance(target.getClassLoader(), new Class[] {target}, this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if("toString".equals( method.getName() )){
            return target.toString();
        }
        if("equals".equals( method.getName() )){
            Object arg = args[0];
            return target.equals(arg);
        }
        HttpRpc annotation = target.getAnnotation(HttpRpc.class);
        if(annotation!=null) {
            ClassInfo classInfo = ClassInfo.create(target, method, args, annotation.serviceName());
            System.out.println("调用的方法名: " + method.getName());
            Object result = RpcService.rpc(classInfo , method.getReturnType() );
            return result;
        }
        return null;
    }
}
